package com.handinglian.ai.notice.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.handinglian.ai.common.util.FastJsonUtil;
import com.handinglian.ai.notice.dto.CensusExcel;
import com.handinglian.ai.notice.dto.ImportCensusDto;
import com.handinglian.ai.notice.entity.Mass;
import com.handinglian.ai.notice.entity.Notice;
import com.handinglian.ai.notice.enums.ImportStateEnum;
import com.handinglian.ai.notice.mapper.MassMapper;
import com.handinglian.ai.notice.service.MassService;
import com.handinglian.ai.notice.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Struct;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MassServiceImpl implements MassService {
    @Autowired
    private MassMapper massMapper;
    @Autowired
    private NoticeService noticeService;

    @Override
    public Integer countByNoticeId(Integer noticeId) {
        return massMapper.countByNoticeId(noticeId);
    }

    @Override
    @Transactional
    public ImportCensusDto importCensusExcel(ModelMap map, HttpServletRequest request, HttpServletResponse response, MultipartFile file, Integer noticeId, String noticeTime, Integer staff) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<CensusExcel> censusExcels = ExcelImportUtil.importExcel(file.getInputStream(),CensusExcel.class, importParams);
        int amountAll = censusExcels.size();
        List<String> phones = censusExcels.stream().map(censusExcel -> censusExcel.getMobilePhone()).collect(Collectors.toList());
        //查询数据库中已存在的电话
        List<String> dbPhones = massMapper.findMobilePhoneByNoticeId(noticeId);
        censusExcels.forEach(censusExcel -> {
            StringBuffer sb = new StringBuffer();
            if (dbPhones.contains(censusExcel.getMobilePhone())){
                sb.append("该电话在数据库中已存在;");
            }
            if (StrUtil.isBlank(censusExcel.getMobilePhone())){
                sb.append("电话不得为null");
            }
            if (Objects.isNull(censusExcel.getAppointmentTime())){
                sb.append("预约时间不得为null或时间格式错误");
            }
            censusExcel.setErrorInfo(sb.toString());
        });

        //数据存在错误则直接返回
        ImportCensusDto importCensusDto = new ImportCensusDto();
        List<CensusExcel> errorCensus = censusExcels.stream().filter(censusExcel -> StrUtil.isNotBlank(censusExcel.getErrorInfo())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(errorCensus)){
            importCensusDto.setErrorNumber(errorCensus.size());
            importCensusDto.setCensusExcels(errorCensus);
            return importCensusDto;
        }
        //对预约时间做一个秒数置0处理
        censusExcels.forEach(censusExcel -> {
            Date apppointmentTime = censusExcel.getAppointmentTime();
            String date = DateUtil.formatDateTime(apppointmentTime);
            date = date.substring(0, date.length()-3)+":00";
            censusExcel.setAppointmentTime(DateUtil.parseDateTime(date));
        });

        List<Mass> addMasses = FastJsonUtil.ListToList(censusExcels, Mass.class);
        addMasses.forEach(mass -> {
            mass.setNoticeId(noticeId);
        });
        int amount = massMapper.batchInsert(addMasses);
        //更新通知
        Notice notice = noticeService.get(noticeId);
        notice.setStaff(staff);

        String date = DateUtil.formatDateTime(DateUtil.offsetMinute(new Date(),2));
        noticeTime = noticeTime.equals("0")? date.substring(0, date.length()-3)+":00":noticeTime;
        notice.setNoticeTime(DateUtil.parseDateTime(noticeTime));
        notice.setImportState(ImportStateEnum.IMPORT.getKey());
        noticeService.update(notice);

        importCensusDto.setSuccessNumber(amount);
        return importCensusDto;
    }

    @Override
    public List<Mass> list(Date noticeTime) {
        return massMapper.list(noticeTime);
    }

    @Override
    @Transactional
    public int delete(Integer id) {
        return massMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public int deleteBatch(List<Integer> ids) {
        return massMapper.deleteByIdIn(ids);
    }
}
